package tv.youxing.android.ui.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.http.VolleyError;
import com.mob.MobApplication;
import com.mob.MobSDK;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import tv.youxing.android.MainActivity;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.UserPwdLoginModel;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;

import static com.mob.MobSDK.getContext;

public class LoginApi implements Callback {
    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR= 2;
    private static final int MSG_AUTH_COMPLETE = 3;

    private OnLoginListener loginListener;
    private String platform;
    private Context context;
    private Handler handler;

    private int loginType=-1;

    public LoginApi() {
        handler = new Handler(Looper.getMainLooper(), this);
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public void setOnLoginListener(OnLoginListener login){
        this.loginListener=login;
    }

    public void login(final Context context,int type) {
        this.context = context.getApplicationContext();
        this.loginType = type;
        if (platform == null) {
            return;
        }

        //初始化SDK
        if(!(context instanceof MobApplication)){
            MobSDK.init(context.getApplicationContext());
        }
        Platform plat = ShareSDK.getPlatform(platform);
        if (plat == null) {
            return;
        }

        if (plat.isAuthValid()) {
            plat.removeAccount(true);
            return;
        }

        //使用SSO授权，通过客户单授权
        plat.SSOSetting(false);
        plat.setPlatformActionListener(new PlatformActionListener() {
            public void onComplete(Platform plat, final int action, HashMap<String, Object> res) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_COMPLETE;
                    msg.arg2 = action;
                    msg.obj =  new Object[] {plat.getName(), res};
                    handler.sendMessage(msg);



                    String openid = plat.getDb().getUserId() + "";
                    String gender = plat.getDb().getUserGender();
                    String head_url = plat.getDb().getUserIcon();
                    String nickname = plat.getDb().getUserName();


//                    Log.e("asd", "sex:" + gender);
//                    Log.e("asd", "openid:" + openid);
//                    Log.e("asd", "avatar_url:" + head_url);
//                    Log.e("asd", "nickname:" + nickname);
//                    Log.e("asd", "platform.getName():" + plat.getName());
//                    Log.e("asd", "plat.getId():" + plat.getId());


//                    Bundle bundle = new Bundle();
//                    bundle.putString("openid",openid);
//                    bundle.putString("avatar_url",head_url);
//                    bundle.putString("nickname",nickname);
//                    bundle.putString("login_type",plat.getName());
//                    Intent intent =new Intent(context, WechatLogin.class);
//                    intent.putExtras(bundle);
//                    context.startActivity(intent);





                    HttpParams params = new HttpParams();
                    params.put("openid",openid);
                    params.put("nickname",nickname);
                    params.put("avatar",head_url);
                    params.put("login_type",loginType);
                    RxVolley.post(StaticClass.thirdPartyLoginURL, params, new HttpCallback() {
                        @Override
                        public void onSuccess(String t) {
                            UserPwdLoginModel userPwdLoginModel = GsonUtils.GsonToBean(t, UserPwdLoginModel.class);

                            if (userPwdLoginModel.getCode() == 200) {
                                ShareUtils.putString(getContext(), AppConst.TOKEN,userPwdLoginModel.getResult().getToken());
                                ShareUtils.putString(getContext(), AppConst.USERNAME,userPwdLoginModel.getResult().getUsername());
                                ShareUtils.putInt(getContext(), AppConst.USERID,userPwdLoginModel.getResult().getUser_id());
                                ShareUtils.putString(getContext(), AppConst.AVATER,userPwdLoginModel.getResult().getAvatar());
                                ShareUtils.putBoolean(getContext(),AppConst.ISLOGIN,true);
                                context.startActivity(new Intent(context, MainActivity.class));
                                Activity activity = (Activity) context;
                                activity.finish();

                            } else {
                                System.out.println("登录失败:"+userPwdLoginModel.getCode());
                                CustomToast.INSTANCE.showToast("登录失败:"+userPwdLoginModel.getCode());
//                               CustomToast.INSTANCE.showToast("登录失败:"+userPwdLoginModel.getCode());
                            }
                        }

                        @Override
                        public void onFailure(VolleyError error) {
                            super.onFailure(error);
                            System.out.println("onFailure:"+error.getMessage());
                        }
                    });
                }
            }

            public void onError(Platform plat, int action, Throwable t) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_ERROR;
                    msg.arg2 = action;
                    msg.obj = t;
                    handler.sendMessage(msg);

                }
                t.printStackTrace();
            }

            public void onCancel(Platform plat, int action) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_CANCEL;
                    msg.arg2 = action;
                    msg.obj = plat;
                    handler.sendMessage(msg);
                }
            }
        });
        plat.showUser(null);
    }

    /**处理操作结果*/
    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_AUTH_CANCEL: {
                // 取消
                Toast.makeText(context, "canceled", Toast.LENGTH_SHORT).show();
            } break;
            case MSG_AUTH_ERROR: {
                // 失败
                Throwable t = (Throwable) msg.obj;
                String text = "caught error: " + t.getMessage();
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
                t.printStackTrace();
            } break;
            case MSG_AUTH_COMPLETE: {
                // 成功
                System.out.println("login 成功");
            } break;
        }
        return false;
    }


    void load() {

    }


}
